<template>
  <dynamic-table
    ref="tableRef"
    :columns="columns"
    :get-list-func="userList"
    :page-option="{ typeId }"
    rowKey="userid"
    :row-selection="rowSelection"
  >
    <template v-slot:title>
      <a-button
        @click="addItem"
        v-permission="{ action: 'user:add', effect: 'disabled' }"
        type="primary"
      >
        添加
      </a-button>
      <a-button @click="deleteItems" :disabled="isDisabled" type="primary">
        删除
      </a-button>
    </template>
  </dynamic-table>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, createVNode, watch, computed, ref } from 'vue'
import { Modal } from 'ant-design-vue'
import { QuestionCircleOutlined } from '@ant-design/icons-vue'
import DynamicTable from '@/components/dynamic-table.vue'
import { useCreateModal } from '@/hooks'
import { userList, userDelete } from '@/api/user'
import AddModal from './add-modal.vue'
import { formatDate } from '@/utils/common'
import { columns } from './columns'
import { hasPermission } from '@/utils/hasPermission'

export default defineComponent({
  name: 'user-list',
  props: ['typeId'],
  components: {
    DynamicTable
  },
  setup(props, ctx) {
    console.log(this, '这哦')
    const tableRef = ref<any>(null)

    const state = reactive({
      data: [],
      uploading: false,
      tableLoading: false,
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          state.rowSelection.selectedRowKeys = selectedRowKeys
        },
        selectedRowKeys: []
      }
    })

    // 表格多选配置项
    const rowSelection = computed(() => ({
      onChange: (selectedRowKeys, selectedRows) => {
        state.rowSelection.selectedRowKeys = selectedRowKeys
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name
      })
    }))

    // 删除多项
    const deleteItems = () => {
      Modal.confirm({
        title: '提示',
        icon: createVNode(QuestionCircleOutlined),
        content: '您确定要删除所有选中吗？',
        onOk: async () => {
          await userDelete({ ids: state.rowSelection.selectedRowKeys, type: props.typeId })
          tableRef.value.refreshTableData()
          state.rowSelection.selectedRowKeys = []
        }
      })
    }
    // 添加策略
    const addItem = () => {
      useCreateModal(AddModal, {
        callback: () => {
          tableRef.value.refreshTableData()
        }
      })
    }
    const isDisabled = computed(
      () => state.rowSelection.selectedRowKeys.length == 0 && hasPermission('user:delete')
    )

    return {
      ...toRefs(state),
      columns,
      tableRef,
      formatDate,
      userList,
      isDisabled,
      addItem,
      deleteItems
    }
  }
})
</script>
